package com.pyi.config.mybatisplus.config;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.net.UnknownHostException;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : zjs
 * @Date: 2019/11/22 11:35
 * Description:
 */
@Configuration
public class MyRedisConfig {


    /**
     * RedisTemplate<Object, Object>   后一个Object若不指定实体类，则缓存时对象必须为Object，否则为指定的实体类
     * 使用RedisTemplate<Object, Object>时： 存入redis的对象不为乱码
     * @param redisConnectionFactory
     * @return
     * @throws UnknownHostException
     */
    @Bean
    public RedisTemplate<Object, Object> myRedisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {

        RedisTemplate<Object,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        template.setDefaultSerializer(serializer);
        return template;
    }


//    @Bean
//    public RedisCacheManager myRedisCacheManager(RedisTemplate<Object,Object> myRedisTemplate){
////        SpringBoot  1.x版本
//        RedisCacheManager cacheManager = new RedisCacheManager(myRedisTemplate);
//        cacheManager.setUsePrefix(true);
//
//        return cacheManager;
//    }

    /**
     * 作用： 所有存入redis的对象不为乱码
     * @param myRedisTemplate
     * @param factory
     * @return
     */
    @Bean
    public RedisCacheManager myRedisCacheManager(RedisTemplate<Object,Object> myRedisTemplate,RedisConnectionFactory factory){
//        SpringBoot  2.x版本
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        cacheConfiguration = cacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair
                            .fromSerializer(myRedisTemplate.getDefaultSerializer()));
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(cacheConfiguration)
                .build();

        return cacheManager;
    }
}
